﻿using Inaction.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace Inaction.Business
{
    internal class ObjectPropertyCompare<T> : IComparer<T> where T : Entity<T>, new()
    {
        private IProperty property;
        private ListSortDirection direction;

        public ObjectPropertyCompare(IProperty property, ListSortDirection direction)
        {
            this.property = property;
            this.direction = direction;
        }

        public int Compare(T x, T y)
        {
            object xValue = property.GetFieldValue(x);
            object yValue = property.GetFieldValue(y);

            int returnValue;

            if (xValue is IComparable)
            {
                returnValue = ((IComparable)xValue).CompareTo(yValue);
            }
            else if (xValue.Equals(yValue))
            {
                returnValue = 0;
            }
            else
            {
                returnValue = xValue.ToString().CompareTo(yValue.ToString());
            }

            if (direction == ListSortDirection.Ascending)
            {
                return returnValue;
            }
            else
            {
                return returnValue * -1;
            }
        }
    }
}
